package com.tanhua.dubbo.utils;


import com.tanhua.domain.mongo.Sequence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

@Component
public class IdService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 获取某个表最新的自增id
     *
     * @return
     */
    public Long getNextId(String tableName) {
        // 更新哪一行数据
        Query query = new Query(Criteria.where("collName").is(tableName));

        // 让seqId字段+1
        Update update = new Update();
        update.inc("seqId");

        // 如果要更新的数据不存在，自动新增一行数据
        mongoTemplate.upsert(query, update, Sequence.class);

        // 查询最新的ID
        Sequence sequence = mongoTemplate.findOne(query, Sequence.class);

        return sequence.getSeqId();
    }
}
